const express = require('express');
const route = express.Router();
const pool = require('../pool');
// 收藏 的添加接口
route.post("/add", (req, res) => {
  var obj = req.body;
  console.log(obj)
  if (!obj.uid) {
    return res.json({ code: 301, msg: "uid is required" });
  }
  if (!obj.cid) {
    return res.json({ code: 302, msg: "cid is required" })
  }
  // 判断收藏表中是否已存在
  let sqlx = "select count(*) as num from favorite where userId=? And courseId=?"
  pool.query(sqlx, [obj.uid, obj.cid], (err, result) => {
    if (err) throw err;
    console.log(result)
    if (result[0].num > 0) { return res.json({ code: 201, msg: "favorite exist" }) } else {
      var ftime = Math.ceil((new Date()).getTime() / 1000);
      let sql = "insert into favorite(userId,courseId,fTime) values(?,?,?)";
      pool.query(sql, [obj.uid, obj.cid, ftime], (err, result) => {
        if (err) throw err;
        if (result.affectedRows > 0) {
          res.json({ code: 200, msg: "shoucang success", data: result.insertId })
        } else {
          res.json({ code: 400, msg: "shou cang fail" })
        }
      })
    }
  });



})
// 收藏的查询接口
route.post("/list", (req, res) => {
  var obj = req.body;
  if (!obj.uid) {
    return res.json({ code: "301", msg: "uid is required" })
  }
  let sql = "select course.cid,course.title,course.pic,course.price,favorite.fTime,favorite.courseId,favorite.userId from course,favorite where course.cid=favorite.courseId And favorite.userId=? order by fTime desc";

  pool.query(sql, [obj.uid], (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      res.json({ code: 200, data: result, msg: "success" })
    } else {
      res.json({ code: 201, msg: "no favorite" })
    }
  })
})
module.exports = route;